'use strict'
import React,{Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  ToolbarAndroid,
  ToastAndroid,
  Image,
  TextInput,
  ListView,
  Dimensions,
} from 'react-native';
import Purelistview from './PureListView'
import Loader from '../component/loader/Loader';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux'
import searchAction from '../actions/searchAction'

import RNFileSearch from '../File/RNFileSearch';

let searchHistory =[];
var width = Dimensions.get('window').width; //full width
var height =Dimensions.get('window').height;
var loadwidth = width/2;
import getStorage from './storage';
var storage = getStorage().getInstance();
export default class SearchScreen  extends Component {

    constructor(props){
      super(props);

     let   ds = new ListView.DataSource({
          rowHasChanged: (r1, r2) => r1 !== r2
      });

      this.state = {
          search: "",
          dataSourceHistory:ds.cloneWithRows(searchHistory),
          isShowResult:false,
          storage:storage,
          searchHistoryObjects:{searchHistory}
        }

    }

    componentDidMount() {

    }
    componentWillMount() {
        this.state.storage.load({
               key:"searchHistory",

        }).then( ret => {
    //如果找到数据，则在then方法中返回
    // console.log(ret.userid);
          //  alert(ret.searchHistory);
          searchHistory = ret.searchHistory;
          this.setState({
              searchHistoryObjects :ret,
              dataSourceHistory:this.state.dataSourceHistory.cloneWithRows(searchHistory)
          });

  }).catch( err => {
    //如果没有找到数据且没有同步方法，
    //或者有其他异常，则在catch中返回
    //console.warn(err);
  })
    }
    componentWillUnmount(){

          this.state.storage.save({
                 key:"searchHistory",
                 rawData: this.state.searchHistoryObjects,
                 expires:null

          });

    }

    render() {
    //   alert(this.props.date);

        return (
          <View style={styles.container}>
                     <ToolbarAndroid
                     navIcon={require('image!abc_ic_ab_back_mtrl_am_alpha')}
                     title = {'搜索'}
                     style={styles.toolbar}
                     onIconClicked={this.props.navigator.pop}
                     >
                     </ToolbarAndroid>

                     <View style={styles.seatchBg}>
                         <TextInput
                            onSubmitEditing ={this.enter.bind(this)}
                             style={styles.searchInput}
                             onChangeText={this._searchText.bind(this)}
                             placeholder="搜索"
                         />
                     </View>
                     {  this.props.isLoading && <View style={{left:loadwidth-33,position:'absolute'}}>
                           <Loader
                              size={37}
                              isVisible ={true}
                                type={'ThreeBounce'}
                              color={'#6d9eeb'}

                              />
                       </View>
                      }

                      { !this.state.isShowResult &&
                        <ListView
                          dataSource={this.state.dataSourceHistory}
                          renderRow={this.renderRowHistory.bind(this)}
                        />

                       }

                      { this.state.isShowResult &&
                        <Purelistview
                          data={this.props.date}
                          renderRow={this.renderRow.bind(this)}
                          renderEmptyList = {this.renderEmpty}
                        />

                       }



         < /View>
        );
    }
       renderEmpty(){
         return (
           <View style={ { flex:1,alignItems: 'center'}}>
              <Text >
                 暂无搜索结果
              </Text>
           </View>
         )
       }

        searchFromHistory(rowDate){
               this.setState({
                search : rowDate
               });
               this.enter();
        }
       renderRowHistory(rowDate){
       return(
       <TouchableOpacity onPress={this.searchFromHistory.bind(this,rowDate)}>
           <View style={styles.resultcontainer}>
                     <Image
                       source={require('./image/search.png')}
                       style={{
                         width: 30,
                         height:30,
                         marginLeft:10,
                         marginTop:10}}
                       ></Image>
                 <View style={styles.rightContainerHistory}>
                   <Text style={styles.title}>{rowDate}</Text>

                 </View>
             </View>

       </TouchableOpacity>
    )

     }
     renderRow(rowDate,l,number){


        return (
               <TouchableOpacity onPress={()=>this._pressRow(rowDate)}>
                   <View style={styles.resultcontainer}>

                         <View style={styles.rightContainer}>
                           <Text style={styles.title}>{rowDate.displayName}</Text>

                         </View>
                     </View>
               </TouchableOpacity>



        );

     }

     _pressRow(file){
       getStorage().getTicket().then( ret => {
         var ticket = ret.Ticket;
         var index = file.nodeRef.lastIndexOf('/');
         var id = file.nodeRef.substring(index+1);
         var url = 'http://42.159.143.17:6080/alfresco/s/api/node/content/workspace/SpacesStore/'+id+'?alf_ticket='+ticket;
         RNFileSearch.openOnlineFile(encodeURI(url),file.name);
       }).catch( err => {

       });
     }


     enter(){



          const {searchAction} = this.props;

          searchAction.search(this.state.search);

              searchHistory.push(this.state.search);
        let   searchHistoryObjects = {searchHistory};


          this.setState({
        //    dataSource: this.state.dataSource.cloneWithRows(this.props.date),
            isShowResult:true,
            searchHistoryObjects:searchHistoryObjects
          });





      }
    _searchText(text) {
        this.setState({
            search: text,
        });
    }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    flexDirection: 'column',
  },
   resultcontainer: {
      height: 70,
      flexDirection: 'row',
      backgroundColor:'#FFFFFF',

    },
  toolbar: {
    backgroundColor: '#6d9eeb',
    height: 56,
  },
  seatchBg: {
        height: 48,
        backgroundColor: '#ececec',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 8,
  },
  searchInput: {
        height: 40,
        shadowColor: '#333',
        backgroundColor: '#fff',
        shadowRadius: 4,
    },
    thumbnail: {
      marginTop:15,
      marginLeft:15,
      width: 40,
      height: 40,

    },
    rightContainer: {
      flex:1,
      marginLeft:5,
          justifyContent: 'center'
    },
    rightContainerHistory: {
      flex:1,
      marginLeft:5,

    },
    title:{
      marginBottom: 8,
      marginTop:10,
      marginLeft:15,
      width:210,
      color:'black',
      fontSize:16
    },
    year:{
      fontSize: 12,
      marginTop:-5,
      marginLeft:15,
    }
});
export default connect(state=>{  return {
  isLoading:state.Search.isLoading,
  date: state.Search.date
 }} ,
  dispatch => {
  return {
     searchAction: bindActionCreators(searchAction, dispatch),
     }}
)(SearchScreen)
